package com.caregiver.watch.business.data.utils;

import com.caregiver.watch.common.constant.NumberConstants;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import static com.caregiver.watch.common.constant.NumberConstants.ZERO;

@Slf4j
public final class ByteUtils {
    public static int loword(int i) {
        return i & 0xFFFF;
    }

    /**
     * 取高位
     *
     * @param i
     * @return
     */
    public static int hiword(int i) {
        return (i & 0xffff0000) >> 16;
    }

    public static byte[] concat(byte[] a, byte[] b) {
        if (a == null) {
            return b;
        } else if (b == null) {
            return a;
        } else {
            byte[] c = new byte[a.length + b.length];
            System.arraycopy(a, 0, c, 0, a.length);
            System.arraycopy(b, 0, c, a.length, b.length);
            return c;
        }
    }

    public static void bytesToHexString(byte[] bytes) {
        StringBuilder hexStringBuilder = new StringBuilder();
        for (byte b : bytes) {
            // Convert the byte to an unsigned int and format it as a two-digit hexadecimal
            hexStringBuilder.append(String.format("%02X", b));
        }
        log.info(hexStringBuilder.toString());
    }

    public static int byteToPositiveInt(byte b){
        int num = b & 0xFF;
        return num;
    }
    public static int bytesToIntBig(byte[] bytes) {
        // Implementation for big-endian byte to int conversion
        int result = 0;
        for (int i = 0; i < bytes.length; i++) {
            result = (result << 8) | (bytes[i] & 0xFF);
        }
        return result;
    }

    /**
     * 获取请求的byte[]数据
     *
     * @param req
     * @return
     */
    public static byte[] getBytes(HttpServletRequest req) {
        int contentLength = req.getContentLength();
        try (ServletInputStream mainstream = req.getInputStream()) {
            byte[] buffer = new byte[contentLength];
            int offset = ZERO;
            int remain = contentLength;
            while (true) {
                int read_size = mainstream.read(buffer, offset, remain);
                if (read_size <= ZERO) {
                    break;
                }
                offset += read_size;
                remain -= read_size;
            }
            ByteUtils.bytesToHexString(buffer);
            return buffer;
        } catch (Exception e) {
            log.error("getBytes error: " + e.getMessage());
        }
        return null;
    }
}
